package com.geline.sqlbackup.util;

import com.alibaba.druid.DbType;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.datasource.DataSourceUtils;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * jdbc解析工具
 * @author: mengx
 * @date: 2021/8/15 15:35
 */
@Slf4j
public class JdbcDbTypeUtil {

    /**
     * 解析为 druid DbType
     * @param jdbcUrl
     * @return
     */
    public static DbType getDbTypeOfDruid(String jdbcUrl) {
        DbType dbType = JdbcDruidUtils.getDbTypeRaw(jdbcUrl, null);
        return dbType;
    }

    /**
     * 解析为 druid DbType
     * @param dataSource
     * @return
     */
    public static DbType getDbTypeOfDruid(DataSource dataSource) {
        Connection connection = null;
        try {
            connection = DataSourceUtils.doGetConnection(dataSource);
            String jdbcUrl = connection.getMetaData().getURL();
            DbType dbType = JdbcDruidUtils.getDbTypeRaw(jdbcUrl, null);
            return dbType;
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                DataSourceUtils.doReleaseConnection(connection, dataSource);
            } catch (SQLException e) {
                log.error("fail to close connection !!!");
            }
        }
        return null;
    }
}
